package com.palfund.autoshowviewpager;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

/**
 * Created by clvc on 2017/7/26.
 * 真正的速度是看不见的 !
 * Today is today , we will go !
 */

public class AutoShowPagerAdapter extends PagerAdapter {
    private int[] mIconIds;
    SparseArray<ImageView> mSparseArray = new SparseArray<>();
    private Context mContext;

    public AutoShowPagerAdapter(Context context, int[] iconIds) {
        mContext = context;
        mIconIds = iconIds;
    }

    @Override
    public int getCount() {
        return mIconIds.length + 2;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageView imageView = mSparseArray.get(position);
        if (imageView == null) {
            imageView = new ImageView(mContext);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            if (position == 0) {
                imageView.setBackgroundResource(mIconIds[mIconIds.length - 1]);
            } else if (position == mIconIds.length + 1) {
                imageView.setBackgroundResource(mIconIds[0]);
            } else {
                imageView.setBackgroundResource(mIconIds[position - 1]);
            }
            mSparseArray.put(position, imageView);
        }
        container.addView(imageView);
        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }
}
